const {Crypto, Utils} = require('icbsc.js');

class SM2Crypto {
  constructor() {}

  /*
   * @ 使用国密 SM2 对字符串进行加密
   * @Param {String} message 需要加密的字符串
   * @Param {String} publicKey 公钥地址
   * @Param {String} cipherMode 加密以后输出结果的顺序, 1 = C1C3C2，0 = C1C2C3，默认为1 (C1=生成随机数的计算出的椭圆曲线点，C2=密文数据，C3=SM3的摘要值)
   */
  encrypt(message, publicKey, cipherMode = 1) {
    const msgBytes = Utils.parseUtf8StringToHex(message);
    return Crypto.sm2.doEncrypt(msgBytes, publicKey, cipherMode);
  }

  /*
   * @ 使用国密 SM2 对字符串进行解密
   * @Param {String} encryptedString 被加密的字符串
   * @Param {String} publicKey 私钥地址
   * @Param {String} cipherMode 第一个参数 encryptedString 加密输出结果的顺序, 1 = C1C3C2，0 = C1C2C3，默认为1 (C1=生成随机数的计算出的椭圆曲线点，C2=密文数据，C3=SM3的摘要值)
   */
  decrypt(encryptedString, privateKey, cipherMode = 1) {
    const res =  Crypto.sm2.doDecrypt(encryptedString, privateKey, cipherMode);
    
    let resstring = ''
    for (var i = 0; i < res.length; i++) {
      resstring += String.fromCharCode(res[i]);
    }
    return resstring
  }

  /*
   * @ 使用国密 SM2 对字符串进行签名
   * @Param {String} message 需要进行签名的字符串
   * @Param {String} privateKey 私钥地址
   */
  sign(message, privateKey) {
    const msgBytes = Utils.parseUtf8StringToHex(message);
    return Crypto.sm2.doSignature(msgBytes, privateKey, {hash: true});
  }

  /*
   * @ 使用国密 SM2 对字符串进行签名验证
   * @Param {String} message 需要验证的字符串
   * @Param {String} signatureData 签名以后生成的字符串
   * @Param {String} publicKey 公钥地址
   */
  verify(message, signatureData, publicKey) {
    const msgBytes = Utils.parseUtf8StringToHex(message);
    return Crypto.sm2.doVerifySignature(msgBytes, signatureData, publicKey, {hash: true});
  }
}

module.exports = {
  sm2: new SM2Crypto()
};

/*
// 测试代码

console.log('sm2 crypto test...');
console.log('==================================================');

var sm2 = new SM2Crypto();

// const privateKey = 'PVT_SM2_2KE9JZiVGKK61RCXvKYMdiQrHWEQv9hkXRBEMFnKZYELHhgGsp';
// const publicKey  = 'PUB_SM2_6uxRi68hARj84RQTxxmBZr5PU7SRefkrcHEY1pRq38bAiwT6xk';

const publicKey =  "PUB_SM2_6UyBXaxziSVhxJo5ZDeFL2bVQWzTiR5KbVPSA4gWkhkW3NeVvs"
const privateKey = "PVT_SM2_2ByjvqpfCtjscomQySLuyQsQMNNnnPEijpWQUGnuVCKeLSaGPd"

let msg = "b19fbcd7abc93de957e6ab9f69043c673a41c55cc2b932f4420b74df7fa87871faae1ab52c6ddb15ad9f0ca7d2dd277eb3be0bfa8d5140b08e024db5ad538a4d000000c9000000c5000000d70000000000000032000000150000004d0000004e6261660472656980793475b16a35736a32686e1b72326a79647075226376742b626f34157161708a753737e5373568626e676914746b7936647461"

let encryptData = sm2.encrypt(msg, publicKey);
console.log("encrypt: " + encryptData);

let doDecryptData = sm2.decrypt(msg, privateKey);
console.log("decrypt: " + doDecryptData);

let signatureData = sm2.sign(msg, privateKey);
console.log('signatureData: ' + signatureData);

let is_valid = sm2.verify(msg, signatureData, publicKey);
console.log('is_valid: ' + is_valid);

console.log('==================================================');

*/